package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;



public class KuangChaoServiceImpl {
	private static Logger logger = Logger.getLogger(KuangChaoServiceImpl.class);
	
	public static KuangChaoServiceImpl service = new KuangChaoServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.KUANGCHAO_ORDER_URL;//"http://121.40.241.198/nettraffic/api/order";
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.KUANGCHAO_ORDERSTATUS_URL; //"http://121.40.241.198/nettraffic/api/transaction2?";
	private static String KUANGCHAO_TOKEN = BetweenProperties.KUANGCHAO_TOKEN;//"1389651247";
	private static String KUANGCHAO_CUSTOMER= BetweenProperties.KUANGCHAO_CUSTOMER;//"apitest";
	
	

	public String order(String pkgNo, String phoneNo, String transNo,String callbackURL) {
      
        String result = "";
        
        String timestamp = String.valueOf(System.currentTimeMillis());
        
        String waitSign = KUANGCHAO_CUSTOMER + KUANGCHAO_TOKEN + timestamp;
        String userKey = getMD5(waitSign.trim());
	
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("customer",KUANGCHAO_CUSTOMER));
        pairList.add(new BasicNameValuePair("product",pkgNo));
        pairList.add(new BasicNameValuePair("timestamp",timestamp));
        pairList.add(new BasicNameValuePair("customerOrderId",transNo));
        pairList.add(new BasicNameValuePair("phone",phoneNo));
        pairList.add(new BasicNameValuePair("effectType","0"));
        pairList.add(new BasicNameValuePair("userKey",userKey));
        pairList.add(new BasicNameValuePair("returnUrl",callbackURL));
    
        logger.info("狂潮订购接口请求参数："+pairList);
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();

		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 狂潮订购请求时的响应statusCode: " + statusCode);

			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "utf-8");
			logger.info("between- 狂潮流量订购请求时的响应数据是:" + result);

		} catch (Exception e) {
			logger.info("between- 狂潮流量订购订购请求时异常是:" + e.getMessage());
			
		}

		return result;
	}
	
	
	public String orderStatus(String cstmOrderNo) {
	
		String customer = KUANGCHAO_CUSTOMER;
	    String timestamp = System.currentTimeMillis()+"";
	    String waitSig =customer+KUANGCHAO_TOKEN+timestamp;
        String userKey = getMD5(waitSig);
	    String result = "";
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("customer",customer));
        pairList.add(new BasicNameValuePair("timestamp",timestamp));
        pairList.add(new BasicNameValuePair("userKey",userKey));
        pairList.add(new BasicNameValuePair("customerOrderId", cstmOrderNo));
       
    	logger.info("between- 狂潮查询状态请求参数:"+pairList);
        String param = "";  
    	
		
		try {
			param = EntityUtils.toString(new UrlEncodedFormEntity(pairList,"utf-8")); 
		
			HttpGet httpGet = new HttpGet(HOST_ORDERSTATUS_PATH+"?"+param);//需要加?拼接
			CloseableHttpClient client = HttpClients.createDefault();
			
			HttpResponse response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 狂潮查询状态的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 狂潮查询状态请求时的响应数据是: " + result+",该订单号："+cstmOrderNo);
			}
		} catch (Exception e) {
			
			logger.info("between- 狂潮查询状态请求时异常: " + e.getMessage());
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("resultCode","2");
			map.put("resultMsg",e.getMessage());
			result = new Gson().toJson(map);
		}
		return result;
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}

	public static void main(String[] args) {
		//String result = new KuangChaoServiceImpl().order("01010001001","13570313596","CX2017", "www.cx.com");
		//System.out.println(result);
		
		String resultjson = new KuangChaoServiceImpl().orderStatus("CX2017");
		System.out.println(resultjson);
	}

}
